package cn.edu.bupt.webapi.demo.controller;

import cn.edu.bupt.webapi.demo.common.Result;
import cn.edu.bupt.webapi.demo.entity.Todo;
import cn.edu.bupt.webapi.demo.mapper.TodoMapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Tag(name = "TodoController v2", description = "利用自定义消息格式的控制器")
@RequestMapping("/api/v2/todos")
public class AnotherTodoController {
    @Resource
    TodoMapper todoMapper;

    @GetMapping(path = "/", produces = "application/json")
    public Result<?> listAll() {
        List<Todo> todos = todoMapper.selectList(null);
        if (todos.isEmpty()) {
            return Result.error(204, "todos为空");
        }
        return Result.ok(todos);
    }

    @GetMapping(path = "/{id}", produces = "application/json")
    public Result<?> getById(@PathVariable("id") Long id) {
        Todo todo = todoMapper.selectById(id);
        if (todo != null) {
            return Result.ok(todo);
        } else {
            return Result.error(404, "该todo不存在");
        }
    }

    @PostMapping(path = "/", consumes = "application/json", produces = "application/json")
    public Result<?> add(@RequestBody Todo todo) {
        todoMapper.insert(todo);
        return Result.ok(todo);
    }


    @DeleteMapping(path = "/{id}")
    public Result<?> delete(@PathVariable Long id) {
        if (todoMapper.deleteById(id) >0) {
            return Result.ok();
        } else {
            return Result.error(204, "该todo不存在，删除失败");
        }
    }

    @PutMapping(path = "/{id}", consumes = "application/json", produces = "application/json")
    public Result<?> update(@PathVariable Long id, @RequestBody Todo todo) {
        todo.setId(id);
        if (todoMapper.updateById(todo) > 0) {
            return Result.ok(todo);
        } else {
            return Result.error(404, "该todo不存在");
        }
    }
}
